package middleware

import (
	"Software/global"
	"Software/model"
	"Software/response"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"time"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token := ctx.GetHeader("Authorization")
		if token == "" {
			response.Response(ctx, 400, nil, "请登录")
			ctx.Abort()
			return
		}

		myClaims, err := ParseToken(token)
		if err != nil {
			response.Response(ctx, 400, nil, "token过期")
			ctx.Abort()
			return
		}
		name := myClaims.Name
		ctx.Set("auditor_name", name)
	}
}

func CreateToken(name string) string {

	mySigningKey := []byte(global.Config.GetString("secretKey"))

	c := model.MyClaims{
		Name: name,
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix(),              // 开始时间
			ExpiresAt: time.Now().Unix() + 24*60*60*2, // 过期时间
			Issuer:    "xubo",                         // 签发人
		},
	}

	t := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	s, e := t.SignedString(mySigningKey)
	if e != nil {
		fmt.Println(e)
	}
	//fmt.Println(s)

	return s
}

func ParseToken(tokenString string) (*model.MyClaims, error) {

	mySigningKey := []byte(global.Config.GetString("secretKey"))

	token, err := jwt.ParseWithClaims(tokenString, &model.MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return mySigningKey, nil
	})

	return token.Claims.(*model.MyClaims), err
}
